package com.haibei.view.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.util.CharArrayBuffer;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import com.common.uitl.LogUtil;
import com.haibei.App;

/**
 * 网络操作工具类 (提供对网络连接、连接类型、解析网络图片等常见网络操作)
 * 
 * @author liunz
 * 
 */
public final class NetUtils {

	private static final String TAG = App.tag;

	/**
	 * 判断是否有可用网络
	 * 
	 * @param context
	 *            设备上下文
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean available = false;
		NetworkInfo[] infos = connec.getAllNetworkInfo();
		if (infos != null) {
			for (NetworkInfo info : infos) {
				if (info.isAvailable() && info.getState() == NetworkInfo.State.CONNECTED) {
					available = true;
					break;
				}
			}
		}
		return available;
	}

	/**
	 * 获取网络连接类型(MOBILE or WIFI)
	 * 
	 * @return
	 */
	public static String getConnectionType(Context context) {
		ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cManager.getActiveNetworkInfo();
		String networkType = "";
		if (networkInfo != null && networkInfo.isAvailable()) {
			int type = networkInfo.getType();
			switch (type) {
			case ConnectivityManager.TYPE_MOBILE: // 手机接入方式
				networkType = "MOBILE";
				break;
			case ConnectivityManager.TYPE_WIFI: // Wifi接入方式
				networkType = "WIFI";
				break;
			}
		}
		return networkType;
	}

	/**
	 * 解析网络图片
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static byte[] readImage(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5 * 1000);
		InputStream inStream = conn.getInputStream();
		return readStream(inStream);
	}

	/**
	 * 将输入流转换成字节数组
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

	/**
	 * 是否是wifi连接
	 * 
	 * @param mContext
	 * @return
	 */
	public static boolean isWifi(Context mContext) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	/**
	 * 获取网络连接类型
	 * 
	 * @param context
	 * @return
	 */
	public static final String getNetType(Context context) {
		String networkType = null;

		try {
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = cm.getActiveNetworkInfo();// NULL

			if (networkInfo != null && networkInfo.isAvailable()) {
				String typeName = networkInfo.getTypeName(); // MOBILE/WIFI
				if (!"MOBILE".equalsIgnoreCase(typeName)) {
					networkType = typeName;
				} else {
					networkType = networkInfo.getExtraInfo(); // cmwap/cmnet/wifi/uniwap/uninet
					if (networkType == null) {
						networkType = typeName + "#[]";
					}
				}
			}

		} catch (Exception e) {
			Log.e(TAG, "getNetType", e);
		}
		Log.d(TAG, "networkType:" + networkType);
		return networkType == null ? "" : networkType;
	}

	/**
	 * 检测用户是否连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isConnect(Context context) {

		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {

				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();

				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		return false;
	}

	/**
	 * 获取网络连接类型
	 * 
	 * @param context
	 * @return
	 */
	public static final int showNetType(Context context) {
		int networkFine = 0;
		String NetType = NetUtils.getNetType(context);
		Log.d("NetType", "NetType :" + NetType);
		if (!android.text.TextUtils.isEmpty(NetType)) {
			if ("WIFI".equalsIgnoreCase(NetType)) {
				networkFine = 1;
			} else if (NetType.toLowerCase().indexOf("3g") != -1) {
				networkFine = 2;
			} else if ("CT".equalsIgnoreCase(NetType.substring(0, 2))) {
				networkFine = 2;
			}
		}
		return networkFine;
	}

	/**
	 * 获取网络连接类型
	 * 
	 * @param context
	 * @return
	 */
	public static final boolean isNetTypeWifiOr3G(Context context) {
		boolean networkFine = false;
		String netType = NetUtils.getNetType(context);
		if (!android.text.TextUtils.isEmpty(netType)) {
			if ("WIFI".equalsIgnoreCase(netType)) {
				networkFine = true;
			} else if (netType.toLowerCase().indexOf("3g") != -1) {
				networkFine = true;
			} else if (netType.toLowerCase().startsWith("CT".toLowerCase())) {
				networkFine = true;
			}
		}
		return networkFine;
	}

	/**
	 * 判断网络连接类型 是否是电信
	 * 
	 * @param context
	 * @return
	 */
	public static final boolean isNetTypeCT(Context context) {
		boolean networkFine = false;
		String NetType = NetUtils.getNetType(context);
		if (!android.text.TextUtils.isEmpty(NetType)) {
			if ("CT".equalsIgnoreCase(NetType.substring(0, 2))) {
				networkFine = true;
			}
		}
		return networkFine;
	}

	/**
	 * 将字符串(以&拼接)转换成map
	 * 
	 * @param str
	 * @return
	 */

	public static Map<String, String> params2Map(String str) {
		String regex = "([^\\?&]+)=([^\\?&]*)";
		HashMap<String, String> paramMap = new HashMap<String, String>();
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		while (m.find()) {
			paramMap.put(m.group(1), m.group(2));
		}
		return paramMap;
	}

	/**
	 * 降map转换成参数字符串(以&拼接)
	 * 
	 * @param paramMap
	 * @return
	 */
	public static String map2params(Map<String, String> paramMap) {
		StringBuilder builder = new StringBuilder();
		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
			// try {
			if (entry.getValue() != null) {
				builder.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
			// } catch (UnsupportedEncodingException e) {
			// Log.e(TAG, "", e);
			// }
		}
		return builder.toString();
	}

	/**
	 * 联通代理
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isUsingWap(Context context) {
		boolean result = false;
		if (isNetworkAvailable(context)) {
			final ConnectivityManager connectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
			if (networkInfo != null) {
				final String netExtraInfo = networkInfo.getExtraInfo();
				if (!TextUtils.isEmpty(netExtraInfo)) {
					if (netExtraInfo.toLowerCase().equalsIgnoreCase("uniwap")
							|| netExtraInfo.toLowerCase().equalsIgnoreCase("3gwap")) {
						result = true;
					}

				}
			}
		}
		return result;
	}

	public static String readFileToString(InputStream instream) throws IOException {
		Reader reader = new InputStreamReader(instream, "UTF-8");
		CharArrayBuffer buffer = new CharArrayBuffer(4 * 1024);
		try {
			char[] tmp = new char[1024];
			int l;
			while ((l = reader.read(tmp)) != -1) {
				buffer.append(tmp, 0, l);
			}
		} finally {
			reader.close();
		}
		return buffer.toString();
	}
}
